package com.financing.wap.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.Pager;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dao.IActivitiesMollionsWealthDao;
import com.financing.wap.dao.IProductDao;
import com.financing.wap.dto.ActivitesMollionsWealthDTO;
import com.financing.wap.dto.FpProjectRabate;
import com.financing.wap.dto.FpShopperProductDTO;
import com.financing.wap.dto.FpVideoDTO;
import com.financing.wap.dto.MailRecordDTO;
import com.financing.wap.dto.ProductAnnualRevenueDTO;
import com.financing.wap.dto.ProductAttachmentDTO;
import com.financing.wap.dto.ProductBasicInfoDTO;
import com.financing.wap.dto.ProductDTO;
import com.financing.wap.dto.ProductDetailPageDTO;
import com.financing.wap.dto.ProductRecommendDTO;
import com.financing.wap.dto.ProjectAccountDTO;
import com.financing.wap.dto.ProjectLikeDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IActivitiesMollionsWealthService;
import com.financing.wap.service.IFpShopperProductService;
import com.financing.wap.service.IFpVideoService;
import com.financing.wap.service.IProductService;
import com.financing.wap.service.IProjectLikeService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.util.NumeralUtil;
import com.financing.wap.vo.ProductAppointmentVO;
import com.financing.wap.vo.ProductProfitAndRebateVO;


@Service("productService")
public class ProductServiceImpl implements IProductService{

	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IProductDao productDao;
	
	@Autowired
	private IActivitiesMollionsWealthService activitesMollionsWealthService;
	
	@Autowired
	private IActivitiesMollionsWealthDao activitiesMollionsWealthDao;
	
	@Autowired
	private IProjectLikeService projectLikeService;

	@Autowired
	private IFpVideoService fpVideoService;
	
	@Autowired
	private IFpShopperProductService fpShopperProductService;
	
	@Override
	public List<ProductDTO> getProductList(Map<String,Object> queryParams, UserDTO user, Pager pager) throws Exception {

		List<ProductDTO> list = this.productDao.getProductList(queryParams, user,pager);

		analyzeProductList(user, list);
		return list;
	}

	private void analyzeProductList(UserDTO user, List<ProductDTO> list) throws Exception {
		for(int i=0; i<list.size(); i++){
			ProductDTO product = list.get(i);
			//基金不查询
			if("01".equals(product.getType())){
				continue;
			}
			Integer productId =product.getId();
			if(product!=null){
				if(SessionUtil.getSession(true).getUser()!=null){
					//如果产品类型是pevc就对收藏 状态做处理
					Map<String, Object> map=new HashMap<String, Object>();
					map.put("faId", SessionUtil.getSession(true).getUser().getId());
					map.put("pId", product.getId());
					ProjectLikeDTO queryProjectLikeType = projectLikeService.queryProjectLikeType(map);
					if(queryProjectLikeType!=null){
						product.setLikeType(queryProjectLikeType.getLikeType());
					}
				}
			}
			
			//产品列表-新增 活动关联
			ActivitesMollionsWealthDTO activitesMollionsWealthDTO = new ActivitesMollionsWealthDTO();
			activitesMollionsWealthDTO.setpId(productId);
			activitesMollionsWealthDTO.setpType(product.getType());
			try {
				product.setActivitiesMollionsWealthList(activitiesMollionsWealthDao.queryActivitiesMollionsWealthList(activitesMollionsWealthDTO));
			} catch (Exception e) {
				logger.error("getProductList queryActivitiesMollionsWealthList error",e);
			}
			
			ProductAnnualRevenueDTO profit = productDao.queryAnnualRevenue(productId,"l");
			ProductAnnualRevenueDTO profitHight = productDao.queryAnnualRevenue(productId,"h");

			ProductAnnualRevenueDTO rebateProfit = productDao.queryAnnualRevenue(productId,"rl");
			ProductAnnualRevenueDTO rebateProfitHight = productDao.queryAnnualRevenue(productId,"rh");


			if(profit==null){
				continue;
			}
			
			product.setProfit(profit);
			product.setProfitHight(profitHight);
			
			profit.setRebate(rebateProfit.getRebate());
			profitHight.setRebate(rebateProfitHight.getRebate());
			profit.setpIsAgreement(rebateProfit.getpIsAgreement());
			profitHight.setpIsAgreement(rebateProfitHight.getpIsAgreement());
			if((user.getId() == null||"1".equals(user.getRole()) || "99".equals(user.getRole()) || "98".equals(user.getRole()))&&profit!=null){
				profit.setRebate(null);
				profitHight.setRebate(null);
				profitHight.setpRebateAmount(null);
			}
			if(Constants.FP_CORP_TYPE_PRIVATE.equals(product.getProjectCorpType())){
				//内销产品 佣金字段为null;
				profit.setRebate(null);
				profitHight.setRebate(null);
				profitHight.setpRebateAmount(null);
			}
			
			//				List<ProductProfitAndRebateVO> profitRebateList = getProductProfitAndRebateList(product.getId());
			//				product.setProfitAndRebateList(profitRebateList);
			//				product.setAppointmentAmount(productDao.queryProductBuyAmount(productId));
			//				product.setAppointmentNumber(productDao.queryProductBuyNumber(productId));
			//平台销售人数及额度。
			Map<String,Object> map = productDao.queryProductBuyNumberAndAmount(productId);

			/***************************所有销售额及销售个数的计算****************************/
			BigDecimal sumAmount = (BigDecimal)map.get("sumAmount");
			Long  num = (Long)map.get("num");
			logger.info("==>project num:"+num);
			logger.info("==>project sumAmount:"+sumAmount);

			if(sumAmount==null){
				sumAmount = new BigDecimal(0);
			}
			if(num==null){
				num = new Long(0);
			}
			logger.info("==>project allSubscriptionNum:"+product.getAllSubscriptionNum());
			logger.info("==>project allSubscriptionAmount:"+product.getAllSubscriptionAmount());
			
			//不需要添加 di
			//product.setAllSubscriptionNum(num.intValue()+product.getAllSubscriptionNum());

			product.setAllSubscriptionNum(num.intValue()+product.getAllSubscriptionNum());
			
			//不需要  添加订单总额 wap_jee_1.7
			//product.setAllSubscriptionAmount(sumAmount.add(product.getAllSubscriptionAmount()));
			product.setAllSubscriptionAmount(product.getAllSubscriptionAmount());
			/***************************所有销售额及销售个数的计算END****************************/

			List<ProductProfitAndRebateVO> profitRebateList = getProductProfitAndRebateList(productId,null);
			product.setAppointmentAmount(sumAmount);
			product.setAppointmentNumber(num); 
			product.setComment(null);
			product.setProfitAndRebateList(profitRebateList);
			
			try {
				ProductAttachmentDTO attachment = new ProductAttachmentDTO();
				attachment.setpId(product.getId());
				List<ProductAttachmentDTO> productAttachments = getProductAttachments(attachment);
				//附件列表
				if(productAttachments==null){
					productAttachments = new ArrayList<ProductAttachmentDTO>();
				}
				product.setProductAttachments(productAttachments);
			} catch (Exception e) {
				logger.error("get productAttachments error",e);
			}
			// 判断产品是否已订阅
			try {
				UserDTO u=SessionUtil.getSession().getUser();
				if(null != u){
					HashMap<String, Object> params = new HashMap<String, Object>();
					params.put("pId", product.getId());
					params.put("uId", u.getId());
					product.setFlagDingYue(queryProductSubBypId(params));
				}
			} catch (Exception e) {
				logger.error("SessionUtil.getSession().getUser() error",e);
			}
			
			
			//添加 视频路演id
			FpVideoDTO  queryVideo = new FpVideoDTO();
			queryVideo.setProductType(product.getType());
			queryVideo.setProductId(product.getId());
			queryVideo = fpVideoService.queryVideoInfo(queryVideo);
			
			product.setSfaVideoId(queryVideo==null?null:queryVideo.getId());
			
			
		}
	}

	@Override
	public List<ProductDetailPageDTO>  getRecommendProduct(Map<String,Object> parames) {
		List<ProductDetailPageDTO>  pageDTOList = this.productDao.getRecommendProduct(parames);
		Double hightRebate = null;
		Double lowRebate = null;
		String hightpIsAgreement = null;
		String lowpIsAgreement = null;
		if(pageDTOList == null)
			return new ArrayList<ProductDetailPageDTO>();
		for(ProductDetailPageDTO pageDTO:pageDTOList){
			hightRebate = new Double(0);
			lowRebate = new Double(100);
			Integer productId = pageDTO.getProductId();
			List<ProductProfitAndRebateVO> profitRebateList = getProductProfitAndRebateList(productId,pageDTO.getCorpType());
			ProductAnnualRevenueDTO profit = productDao.queryAnnualRevenue(productId,"l");
			ProductAnnualRevenueDTO profitHight = productDao.queryAnnualRevenue(productId,"h");
			
			//产品列表-新增 活动关联
			ActivitesMollionsWealthDTO activitesMollionsWealthDTO = new ActivitesMollionsWealthDTO();
			activitesMollionsWealthDTO.setpId(productId);
			activitesMollionsWealthDTO.setpType(pageDTO.getProductType());
			try {       
				pageDTO.setActivitiesMollionsWealthList(activitiesMollionsWealthDao.queryActivitiesMollionsWealthList(activitesMollionsWealthDTO));
			} catch (Exception e) {
				logger.error("getProductList queryActivitiesMollionsWealthList error",e);
			}
			
			
			//内销产品返佣率为null
			if(profit==null){
				continue;
			}
			//产品内销返佣率为null处理
			if(Constants.FP_CORP_TYPE_PRIVATE.equals(pageDTO.getCorpType())){ 
				//内销产品 佣金字段为null;
				if(profitHight!=null){
					profit.setRebate(null);
					profitHight.setRebate(null);
				}
			}else{
				for(ProductProfitAndRebateVO profitVo:profitRebateList){
					if(hightRebate<profitVo.getRebate()){
						hightRebate = profitVo.getRebate();
						hightpIsAgreement = profitVo.getpIsAgreement();
					}
					if(lowRebate>profitVo.getRebate()){
						lowRebate = profitVo.getRebate();
						lowpIsAgreement = profitVo.getpIsAgreement();
					}
				}
				profit.setRebate(lowRebate);
				profit.setpIsAgreement(lowpIsAgreement);
				profitHight.setRebate(hightRebate);
				profitHight.setpIsAgreement(hightpIsAgreement);
			}

			pageDTO.setProfitAndRebateList(profitRebateList);
			pageDTO.setProfit(profit);
			pageDTO.setProfitHight(profitHight);
			//产品内销处理END

			if(!profitRebateList.isEmpty()){
				ProductProfitAndRebateVO minVO = profitRebateList.get(0);
				if(Constants.FP_CORP_TYPE_PRIVATE.equals(pageDTO.getCorpType())){
					//内销产品 佣金字段为null;
					pageDTO.setMinRebate(null);  //返利值
				}else{
					pageDTO.setMinRebate(minVO.getRebate());  //返利值
				}
				pageDTO.setAnnualRevenueExpect(minVO.getExpectAnnualRevenue());
//				pageDTO.setMinimumAmount(minVO.getStartAmount());

				pageDTO.setRebateIsRatio(minVO.getRebateIsRatio()); //返利类型
			}

			//TODO 募集进度， 预约人数
			Map<String,Object> map = productDao.queryProductBuyNumberAndAmount(productId);

			/***************************所有销售额及销售个数的计算****************************/
			BigDecimal sumAmount = (BigDecimal)map.get("sumAmount");
			Long  num = (Long)map.get("num");
			logger.info("==>project num:"+num);
			logger.info("==>project sumAmount:"+sumAmount);

			if(sumAmount==null){
				sumAmount = new BigDecimal(0);
			}
			if(num==null){
				num = new Long(0);
			}
			logger.info("==>project allSubscriptionNum:"+pageDTO.getAllSubscriptionNum());
			logger.info("==>project allSubscriptionAmount:"+pageDTO.getAllSubscriptionAmount());

			pageDTO.setAllSubscriptionNum(num.intValue()+pageDTO.getAllSubscriptionNum());
			pageDTO.setAllSubscriptionNum(num.intValue()+pageDTO.getAllSubscriptionNum());
			//不需要  添加订单总额 wap_jee_1.7
			//pageDTO.setAllSubscriptionAmount(sumAmount.add(pageDTO.getAllSubscriptionAmount()));
			pageDTO.setAllSubscriptionAmount(pageDTO.getAllSubscriptionAmount());
			/***************************所有销售额及销售个数的计算END****************************/
			pageDTO.setAppointmentAmount((BigDecimal)map.get("sumAmount"));
			pageDTO.setAppointmentNumber((Long)map.get("num")); 
			
			//滞空的字段
			pageDTO.setSummary(null);
			pageDTO.setRiskRankComtent(null);
			
		}


		return pageDTOList;
	}



	/**
	 * 获得产品收益率，返佣
	 * @param productId
	 * @return
	 */
	public List<ProductProfitAndRebateVO> getProductProfitAndRebateList(Integer productId,String corpType){
		List<FpProjectRabate> rebateList = productDao.getProductProfitRebateList(productId);
		List<ProductProfitAndRebateVO> retList = new ArrayList<ProductProfitAndRebateVO>(rebateList.size());
		for(FpProjectRabate rebate : rebateList){ //最低返利，收益率
			ProductProfitAndRebateVO vo = new ProductProfitAndRebateVO();
			retList.add(vo);
			vo.setExpectAnnualRevenue(rebate.getAnnualRevenue().getPAnnualRevenueExpect());
			vo.setStartAmount(rebate.getAnnualRevenue().getPStartAmount());
			vo.setEndAmount(rebate.getAnnualRevenue().getPEndAmount());
			vo.setpIsAgreement(rebate.getpIsAgreement());
			Double s=rebate.getpRebateAmount()==null?null:rebate.getpRebateAmount().doubleValue();
			vo.setpRebateAmount(s);
			UserDTO loginUser = SessionUtil.getSession().getUser();
			String type =loginUser==null?"": loginUser.getUType();
			if(Constants.FA_TYPE_CORP.equals(type)){
				vo.setSellingPrice(rebate.getpSellingPrice());
			}
			if(!Constants.FP_CORP_TYPE_PRIVATE.equals(corpType)){
				vo.setRebate(rebate.getPRabateProfit().doubleValue());  //返利值
				vo.setRebateIsRatio(CommonConstantUtil.isRatio(rebate.getPRabateType())); //返利类型
			}
		}
		/**排序*/
		ProductProfitAndRebateVO comparator=new ProductProfitAndRebateVO();
		Collections.sort(retList,comparator);
		/***/
		return retList;
	}
	
	/**
	 * 获得产品收益率，返佣 (包括销售、核心、成本)
	 * @param productId
	 * @return
	 */
	public List<ProductProfitAndRebateVO> getProductProfitAndRebateListByPrice(Integer productId,String corpType){
		
		List<FpProjectRabate> rebateList = productDao.getProductProfitRebateList(productId);
		List<ProductProfitAndRebateVO> retList = new ArrayList<ProductProfitAndRebateVO>(rebateList.size());
		for(FpProjectRabate rebate : rebateList){ //最低返利，收益率
			ProductProfitAndRebateVO vo = new ProductProfitAndRebateVO();
			retList.add(vo);
			vo.setExpectAnnualRevenue(rebate.getAnnualRevenue().getPAnnualRevenueExpect());
			vo.setStartAmount(rebate.getAnnualRevenue().getPStartAmount());
			vo.setEndAmount(rebate.getAnnualRevenue().getPEndAmount());
			if(!Constants.FP_CORP_TYPE_PRIVATE.equals(corpType)){
				vo.setRebate(rebate.getPRabateProfit().doubleValue());  //返利值 挂网
				vo.setSellingPrice(rebate.getpSellingPrice()); //销售价
				vo.setCorePrice(rebate.getpCorePrice()); //核心价
				vo.setCostPrice(rebate.getpCostPrice()); //成本价
				vo.setRebateIsRatio(CommonConstantUtil.isRatio(rebate.getPRabateType())); //返利类型
				// ————订单流程改造 增加后端价格
				if(null == rebate.getpBackRabateProfit()){
					vo.setBackRabate(new Double("0"));
				}else{
					vo.setBackRabate(rebate.getpBackRabateProfit().doubleValue());
				}
				vo.setBackSellingPrice(rebate.getpBackSellingPrice());
				vo.setCoreBackPrice(rebate.getpCoreBackPrice());
				vo.setCostBackPrice(rebate.getpCostBackPrice());
				vo.setpIsAgreement(rebate.getpIsAgreement());
				// 返佣表中的id用户有单模式
				vo.setId(rebate.getId());
			}
		}
		/**排序*/
		ProductProfitAndRebateVO comparator=new ProductProfitAndRebateVO();
		Collections.sort(retList,comparator);
		/***/
		return retList;
	}
	@SuppressWarnings("unchecked")
	@Override
	public ProductDetailPageDTO getProductDetailView(Integer productId) throws Exception {
		ProductDetailPageDTO pageDTO = productDao.getProductDetailPage(productId); //获得产品信息
		
		//做热搜榜处理
		if(null!=pageDTO){
			Integer counts =  (Integer)MemcacheCacheHelper.mcc.get("productName_"+productId);
			if(counts==null){
				counts=0;
			}
			MemcacheCacheHelper.mcc.set("productName_"+productId, (counts+1));
			
			Object  mapObjecct = MemcacheCacheHelper.mcc.get("productName_map");
			if(mapObjecct != null && mapObjecct instanceof Map){
				Map<Integer,Integer> pMap = (HashMap<Integer,Integer>)MemcacheCacheHelper.mcc.get("productName_map");
				pMap.put(productId, counts+1);
				MemcacheCacheHelper.mcc.set("productName_map", pMap);
			}else{
				Map<Integer,Integer> pNewMap = new HashMap<Integer,Integer>();
				pNewMap.put(productId, counts+1);	
				MemcacheCacheHelper.mcc.set("productName_map", pNewMap);
			}
			
		}
		UserDTO user=SessionUtil.getSession(true).getUser();
		if(pageDTO!=null){
			if(user!=null){
				//如果产品类型是pevc就对收藏 状态做处理
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("faId", user.getId());
				map.put("pId", pageDTO.getId());
				ProjectLikeDTO queryProjectLikeType = projectLikeService.queryProjectLikeType(map);
				if(queryProjectLikeType!=null){
					pageDTO.setLikeType(queryProjectLikeType.getLikeType());
				}
			}
		}
		
		Double hightRebate = new Double(0); 
		Double lowRebate = new Double(100);
		if(pageDTO == null)
			return new ProductDetailPageDTO();
		List<ProductProfitAndRebateVO> profitRebateList = getProductProfitAndRebateList(productId,pageDTO.getCorpType());
//		ProductProfitAndRebateVO comparator=new ProductProfitAndRebateVO();
//		Collections.sort(profitRebateList,comparator);
		
		//百万财富活动
		String productType = pageDTO.getProductType();
		try {
			pageDTO.setActivitiesMollionsWealth(activitesMollionsWealthService.queryActivitiesMollionsWealth(productId,productType));
		} catch (Exception e) {
			Log.error("activities mollions wealth!",e);
		}
		//产品列表-新增 活动关联
		ActivitesMollionsWealthDTO activitesMollionsWealthDTO = new ActivitesMollionsWealthDTO();
		activitesMollionsWealthDTO.setpId(productId);
		activitesMollionsWealthDTO.setpType(productType);
		try {
			pageDTO.setActivitiesMollionsWealthList(activitiesMollionsWealthDao.queryActivitiesMollionsWealthList(activitesMollionsWealthDTO));
		} catch (Exception e) {
			logger.error("getProductList queryActivitiesMollionsWealthList error",e);
		}
		// 返佣 预期年化 添加非空 判断  -lisu
		ProductAnnualRevenueDTO profit = productDao.queryAnnualRevenue(productId,"l");
		profit = profit == null?new ProductAnnualRevenueDTO():profit;
		ProductAnnualRevenueDTO profitHight = productDao.queryAnnualRevenue(productId,"h");
		profitHight = profitHight == null?new ProductAnnualRevenueDTO():profitHight;
		
		//产品内销返佣率为null处理
		if(Constants.FP_CORP_TYPE_PRIVATE.equals(pageDTO.getCorpType())){ 
			//内销产品 佣金字段为null;
			if(profitHight!=null){
				profit.setRebate(null);
				profitHight.setRebate(null);
			}
		}else{
			for(ProductProfitAndRebateVO profitVo:profitRebateList){
				if((user == null||"1".equals(user.getRole()) || "99".equals(user.getRole()) || "98".equals(user.getRole()))&&profit!=null){
					profitVo.setRebate(null);
				}else{
					if(hightRebate<profitVo.getRebate()){
						hightRebate = profitVo.getRebate();
					}
					if(lowRebate>profitVo.getRebate()){
						lowRebate = profitVo.getRebate();
					}
				}
			}
			if((user == null||"1".equals(user.getRole()) || "99".equals(user.getRole()) || "98".equals(user.getRole()))&&profit!=null){
				profit.setRebate(null);
				profitHight.setRebate(null);
			}else{
				profit.setRebate(lowRebate);
				profitHight.setRebate(hightRebate);
			}
		}
		pageDTO.setProfitAndRebateList(profitRebateList);
		pageDTO.setProfit(profit);
		pageDTO.setProfitHight(profitHight);
		//产品内销返佣率为null处理END
		if(!profitRebateList.isEmpty()){
			ProductProfitAndRebateVO minVO = profitRebateList.get(0);
			pageDTO.setAnnualRevenueExpect(minVO.getExpectAnnualRevenue());
			if(Constants.FP_CORP_TYPE_PRIVATE.equals(pageDTO.getCorpType())){
				//内销产品 佣金字段为null;
				pageDTO.setMinRebate(null);  //返利值
			}else{
				pageDTO.setMinRebate(minVO.getRebate());  //返利值
			}

		}


		//TODO 募集进度， 预约人数
		Map<String,Object> map = productDao.queryProductBuyNumberAndAmount(productId);
		BigDecimal sumAmount = (BigDecimal)map.get("sumAmount");
		Long  num = (Long)map.get("num");
		logger.info("==>project num:"+num);
		logger.info("==>project sumAmount:"+sumAmount);
		if(sumAmount==null){
			sumAmount = new BigDecimal(0);
		}
		if(num==null){
			num = new Long(0);
		}
		logger.info("==>project allSubscriptionNum:"+pageDTO.getAllSubscriptionNum());
		logger.info("==>project allSubscriptionAmount:"+pageDTO.getAllSubscriptionAmount());

		pageDTO.setAllSubscriptionNum(num.intValue()+pageDTO.getAllSubscriptionNum());

		//不需要添加订单总额
		//pageDTO.setAllSubscriptionAmount(sumAmount.add(pageDTO.getAllSubscriptionAmount()));
		pageDTO.setAllSubscriptionAmount(pageDTO.getAllSubscriptionAmount());

		pageDTO.setAppointmentAmount((BigDecimal)map.get("sumAmount"));
		pageDTO.setAppointmentNumber((Long)map.get("num")); 
		
		
		//添加 视频路演id
		FpVideoDTO  queryVideo = new FpVideoDTO();
		queryVideo.setProductType(pageDTO.getProductType());
		queryVideo.setProductId(pageDTO.getProductId());
		queryVideo = fpVideoService.queryVideoInfo(queryVideo);
		
		//session 未空的时候 ，清空 视频密码
		/*if(SessionUtil.getSession(true).getUser() == null && queryVideo!= null){
			queryVideo.setEncryptionPassword(null);
		}*/
		
		pageDTO.setSfaVideo(queryVideo);
		
		//产品其他信息fp_shopper_product
		if(pageDTO !=null && user != null) {
			FpShopperProductDTO  fsp = new FpShopperProductDTO();
			fsp.setProductId(pageDTO.getProductCode());
			fsp.setFlagTuijian("1");
			fsp.setDeleteTag("1");
			fsp.setUserId(user.getId());
			FpShopperProductDTO fspDTO = fpShopperProductService.queryListGetFirst(fsp);
			pageDTO.setFpsDto(fspDTO);
		}
		
		return pageDTO;
	}

	@Override
	public ProductDetailPageDTO getProductView(Integer productId) throws Exception {

		ProductDetailPageDTO bean = productDao.getProductDetailPage(productId); //获得产品信息;

		if(bean != null) {
			ProductAnnualRevenueDTO profit = productDao.queryAnnualRevenue(bean.getProductId(), "l");
			ProductAnnualRevenueDTO profitHight = productDao.queryAnnualRevenue(bean.getProductId(), "h");

			bean.setProfit(profit);
			bean.setProfitHight(profitHight);
		}
		return bean;
	}

	@Override
	public ProductDetailPageDTO getProductDetailViewByprice(Integer productId) {
		ProductDetailPageDTO pageDTO = productDao.getProductDetailPage(productId); //获得产品信息
		Double hightRebate = new Double(0);
		Double lowRebate = new Double(100);
		if(pageDTO == null)
			return new ProductDetailPageDTO();
		// ————订单流程改造	新增后端相关价格
		List<ProductProfitAndRebateVO> profitRebateList = getProductProfitAndRebateListByPrice(productId,pageDTO.getCorpType());
//		ProductProfitAndRebateVO comparator=new ProductProfitAndRebateVO();
//		Collections.sort(profitRebateList,comparator);
		
		//百万财富活动
		try {
			pageDTO.setActivitiesMollionsWealth(activitesMollionsWealthService.queryActivitiesMollionsWealth(productId,pageDTO.getProductType()));
		} catch (Exception e) {
			Log.error("activities mollions wealth!",e);
		}

		
		// 返佣 预期年化 添加非空 判断  -lisu
		ProductAnnualRevenueDTO profit = productDao.queryAnnualRevenue(productId,"l");
		profit = profit == null?new ProductAnnualRevenueDTO():profit;
		ProductAnnualRevenueDTO profitHight = productDao.queryAnnualRevenue(productId,"h");
		profitHight = profitHight == null?new ProductAnnualRevenueDTO():profit;
		
		//产品内销返佣率为null处理
		if(Constants.FP_CORP_TYPE_PRIVATE.equals(pageDTO.getCorpType())){ 
			//内销产品 佣金字段为null;
			if(profitHight!=null){
				profit.setRebate(null);
				profitHight.setRebate(null);
			}
		}else{
			for(ProductProfitAndRebateVO profitVo:profitRebateList){
				if(hightRebate<profitVo.getRebate()){
					hightRebate = profitVo.getRebate();
				}
				if(lowRebate>profitVo.getRebate()){
					lowRebate = profitVo.getRebate();
				}
			}
			profit.setRebate(lowRebate);
			profitHight.setRebate(hightRebate);
		}
		pageDTO.setProfitAndRebateList(profitRebateList);
		pageDTO.setProfit(profit);
		pageDTO.setProfitHight(profitHight);
		//产品内销返佣率为null处理END
		if(!profitRebateList.isEmpty()){
			ProductProfitAndRebateVO minVO = profitRebateList.get(0);
			pageDTO.setAnnualRevenueExpect(minVO.getExpectAnnualRevenue());
			if(Constants.FP_CORP_TYPE_PRIVATE.equals(pageDTO.getCorpType())){
				//内销产品 佣金字段为null;
				pageDTO.setMinRebate(null);  //返利值
			}else{
				pageDTO.setMinRebate(minVO.getRebate());  //返利值
			}

		}


		//TODO 募集进度， 预约人数
		Map<String,Object> map = productDao.queryProductBuyNumberAndAmount(productId);
		BigDecimal sumAmount = (BigDecimal)map.get("sumAmount");
		Long  num = (Long)map.get("num");
		logger.info("==>project num:"+num);
		logger.info("==>project sumAmount:"+sumAmount);
		if(sumAmount==null){
			sumAmount = new BigDecimal(0);
		}
		if(num==null){
			num = new Long(0);
		}
		logger.info("==>project allSubscriptionNum:"+pageDTO.getAllSubscriptionNum());
		logger.info("==>project allSubscriptionAmount:"+pageDTO.getAllSubscriptionAmount());

		pageDTO.setAllSubscriptionNum(num.intValue()+pageDTO.getAllSubscriptionNum());
		//不需要添加订单总额
		//pageDTO.setAllSubscriptionAmount(sumAmount.add(pageDTO.getAllSubscriptionAmount()));
		pageDTO.setAllSubscriptionAmount(pageDTO.getAllSubscriptionAmount());
		pageDTO.setAppointmentAmount((BigDecimal)map.get("sumAmount"));
		pageDTO.setAppointmentNumber((Long)map.get("num")); 
		return pageDTO;
	}



	@Override
	public ProductAppointmentVO calcProductAppointmenAndSigning(Integer productId) {
		List<Map<String, Object>> list = productDao.getProductOrderStat(productId);
		int appointmentNum = 0; //预约数
		BigDecimal appointmentAmount = new BigDecimal(0);
		int signingNum = 0; //签约数
		BigDecimal signingAmount = new BigDecimal(0);
		for(Map<String, Object> map : list){
			Integer status = (Integer)map.get("status");
			BigDecimal amount = (BigDecimal)map.get("amount");
			if(CommonConstantUtil.isAppointmentOrder(status)){
				if(amount != null)
					appointmentAmount = NumeralUtil.add(amount, appointmentAmount);
				appointmentNum += (Long)map.get("count");
			}
			if(CommonConstantUtil.isSigningOrder(status)){
				if(amount != null)
					signingAmount = NumeralUtil.add(amount, signingAmount);
				signingNum += (Long)map.get("count");
			}
		}

		ProductAppointmentVO vo = new ProductAppointmentVO();
		vo.setAppointmentAmount(appointmentAmount);
		vo.setAppointmentNum(appointmentNum);
		vo.setSigningAmount(signingAmount);
		vo.setSigningNum(signingNum);

		return vo;
	}

	public Integer getProductIdByProductCode(String productCode){
		return productDao.getProductIdByProductCode(productCode);
	}

	@Override
	public List<ProjectAccountDTO> queryProjectAccount(int projectId) {
		return productDao.queryProjectAccount(projectId);
	}

	@Override
	public int getProductListCount(Map<String, Object> queryParams, UserDTO user) {
		int count = this.productDao.getProductListCount(queryParams, user);
		return count;
	}

	@Override
	public List<ProductAttachmentDTO> getProductAttachments(ProductAttachmentDTO  a) {
		return productDao.getProductAttachments(a);
	}

	@Override
	public Integer insertMailRecord(MailRecordDTO mailRecordDTO) {
		return productDao.insertMailRecord(mailRecordDTO);
	}
	
	@Override
	public List<Map> querySiteMapProjectList(){
		return productDao.querySiteMapProjectList();
	}
	
	@Override
	public List<Map> querySiteMapFundList(){
		return productDao.querySiteMapFundList();
	}
	
	@Override
	public List<Map> querySiteMapActivitiesList(){
		return productDao.querySiteMapActivitiesList();
	}

	@Override
	public List<Map> querySiteMapProjectCompanyList() {
		return productDao.querySiteMapProjectCompanyList();
	}

	@Override
	public Map<String, Integer> queryProjectAmountCount() {
		return productDao.queryProjectAmountCount();
	}

	@Override
	public int getProductPEVCListCount(Map<String,Object> params) {
		return productDao.getProductPEVCListCount(params);
	}

	@Override
	public List<ProductDTO> getProductPEVCList(Map<String, Object> params) throws Exception {
		List<ProductDTO> list = productDao.getProductPEVCList(params);
		//对结果集解析
		analyzeProductList((UserDTO)params.get("user"), list);
		return list;
	}

	@Override
	public List<ProductDTO> getProductName() {
		return productDao.getProductName();
	}
	@Override
	public List<ProductDTO> getProductByType(Map<String, Object> queryParams)
			throws Exception {
		return productDao.getProductByType(queryParams);
	}
		@Override
	public Boolean queryProductSubBypId(Map<String, Object> params) {
		int subTimes = productDao.queryProductSubBypId(params);
		if(0 == subTimes){
			return false;
		}
		return true;
	}

		@Override
		public List<Map<String, Object>> getMediaSourceProduct(
				Map<String, Object> map) throws SQLException {
			 List<Map<String, Object>> mediaSourceProduct = productDao.getMediaSourceProduct(map);
				for (int i = 0; i < mediaSourceProduct.size(); i++) {
					try {
						 ProductAnnualRevenueDTO profitHight =new ProductAnnualRevenueDTO();
						 ProductAnnualRevenueDTO p=productDao.queryCurrentAnnualRevenue(Integer.parseInt(String.valueOf(mediaSourceProduct.get(i).get("id"))),"h");
						 if(p!=null)
							 profitHight.setExpectAnnualRevenue(p.getExpectAnnualRevenue());
						 else{
							 profitHight.setExpectAnnualRevenue("0");
						 }
						 mediaSourceProduct.get(i).put("profitHight",profitHight);
					} catch (Exception e) {
						logger.error("get profitHight error",e);
					}
				}
			 return mediaSourceProduct;
		}

		@Override
		public List<ProductRecommendDTO> getRecommendFundProduct() {
			// 推荐列表添加私募
			return this.productDao.getRecommendFundProduct();
		}
		
		@SuppressWarnings("unchecked")
		@Override
		public ProductDetailPageDTO getProductDetailPage(Integer productId) throws Exception {
			return productDao.getProductDetailPage(productId); //获得产品信息
		}

		@Override
		public ProductBasicInfoDTO queryBasicInfo(String code) {
			return productDao.queryBasicInfo(code);
		}

		@Override
		public ProductBasicInfoDTO queryAllProductBasicInfo(String code) {
			return productDao.queryAllProductBasicInfo(code);
		}

	@Override
	public List<ProductDTO> getRecommendProductForProductInfo(Map<String, Object> map) throws Exception {

		List<ProductDTO> productList = productDao.getRecommendProductForProductInfo(map);

		for (ProductDTO product:productList){
			ProductAnnualRevenueDTO profit = productDao.queryAnnualRevenue(product.getId(),"l");
			ProductAnnualRevenueDTO profitHight = productDao.queryAnnualRevenue(product.getId(),"h");

			product.setProfit(profit);
			product.setProfitHight(profitHight);
		}

		return productList;
	}

	@Override
	public String getProductNameByProductCode(String param) {
		return productDao.getProductNameByProductCode(param);
	}
}
